<?php
namespace Home\Controller;

use Utuo\DistributionShopForeground;

/**
 * 支付调试接口
 * @author song
 */
class DisShopPayDebugController extends DistributionShopForeground {
	
	public function _init() {
		layout('disshop');
		$this->setModelName("DistributionShop");
		$this->setModelControllerName("DisShop");
		if ( in_array(ACTION_NAME, array('notify')) ) {
			$this->setCheckLogin(false);
		}
	}
	
	/**
	 * 通知回调连接
	 */
	public function notifyAction() {
		$apitype = I('get.apitype', ''); // 获得支付方式
		$pay = \Utuo\Pay::getInstance($apitype, $this->getApiConfig(array('paymentMethod' => $apitype)));
		switch ($apitype) {
			case "Tenpay":
				$paramNames = "sign_type,service_version,input_charset,sign,sign_key_index,trade_mode,trade_state,pay_info,partner,bank_type,bank_billno,total_fee,fee_type,notify_id,transaction_id,out_trade_no,attach,time_end,transport_fee,product_fee,discount,buyer_alias";
				foreach(explode(",", $paramNames) as $v) {
					$notify[$v] = $_REQUEST[$v];
				}
				if( $pay->verifyNotify($notify) ) {
					$this->paySuccess($notify["out_trade_no"], $apitype);
				}
				exit();
			case "WxTenpay":
				if (isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
					// 处理数据
					$notify = (array) simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA'], 'SimpleXMLElement', LIBXML_NOCDATA);
					if( $pay->verifyNotify($notify) ) {
						$this->paySuccess($notify["out_trade_no"], $apitype);
						exit("<xml><return_code>SUCCESS</return_code></xml>");
					}
				} else {
					exit("<xml><return_code>FAIL</return_code></xml>");
				}
			default:
				exit("<xml><return_code>FAIL</return_code></xml>");
		}
	}
	
	/**
	 * 支付成功时
	 * @param unknown $orderId
	 * @param unknown $apitype
	 */
	protected function paySuccess($orderId, $apitype) {
		$productOrder = M("DistributionShopOrder")->where("order_id='%s'", $orderId)->find();
		if ( $productOrder['pay_status'] == \My\Model\ProductOrderModel::PAY_STATUS_NOT_PAID ) {
			M("DistributionShopOrder")->where("id=%d", $productOrder['id'])
									  ->save(array(
									  		"order_status" => \My\Model\ProductOrderModel::ORDER_STATUS_SHIPPING, 
											"pay_method" => $apitype, 
											"pay_status" => \My\Model\ProductOrderModel::PAY_STATUS_PAID
									  	));
		}
	}
	
	
	/**
	 * 获得接口配置
	 * @param unknown $cid
	 * @param unknown $settlementModes
	 * @return array
	 */
	protected function getApiConfig( $cfg ) {
		// 获得支付接口
		$productPayApi = D("ProductPayApi")->where("cid=%d and tag='%s'", $this->cid, $cfg['paymentMethod'])->find(); // 获得支付方式配置
		$config = (array)unserialize($productPayApi['cfg']);
		if ( 'WxTenpay' == $cfg['paymentMethod']) { // 微信支付时读取开发者配置
			$wechat = M('Wechat')->where(array('cid'=>$this->cid))->find();
			$config = array_merge($config, array('appid' => $wechat['appid'], 'appsecret' => $wechat['appsecret'], ));
		}
		return $config;
	}
	
}